#include "def.h"
#include "2410addr.h"
#include "2410lib.h"
#include "2410slib.h"
#include "uart.h"
#include "timer.h"
#include "led.h"
#include "timer.h"


U32	Console_Uart = 0;
U32	Console_Baud = 115200;


static void cal_cpu_bus_clk(void)
{
	U32 val;
	U8 m, p, s;
	
	val = rMPLLCON;
	m = (val>>12)&0xff;
	p = (val>>4)&0x3f;
	s = val&3;

	SYS_FCLK = ((m+8)*(FIN/100)*2)/((p+2)*(1<<s))*100;
	
	val = rCLKDIVN;
	m = (val>>1)&3;
	p = val&1;	
	val = rCAMDIVN;
	s = val>>8;
	
	switch (m) {
	case 0:
		SYS_HCLK = SYS_FCLK;
		break;
	case 1:
		SYS_HCLK = SYS_FCLK>>1;
		break;
	case 2:
		if(s&2)
			SYS_HCLK = SYS_FCLK>>3;
		else
			SYS_HCLK = SYS_FCLK>>2;
		break;
	case 3:
		if(s&1)
			SYS_HCLK = SYS_FCLK/6;
		else
			SYS_HCLK = SYS_FCLK/3;
		break;
	}
	
	if(p)
		SYS_PCLK = SYS_HCLK>>1;
	else
		SYS_PCLK = SYS_HCLK;

	rUPLLCON = (56<<12) | (2<<4) | 2;
}


int Main(U32 RstStat)
{
	ChangeMPllValue(92,1,1);    //400MHZ
	SetClockDivider(2,1);		//fclk:hclk:pclk=1:4:8
	cal_cpu_bus_clk();	
	rGPHCON=(rGPHCON&0x3ffff)|(0x0a<<18);
	rMISCCR=(rMISCCR&0x0f)|(0x02<<4);
    rMISCCR=(rMISCCR&0x0f)|(0x03<<4);  
    rMISCCR=(rMISCCR&0x0f)|(0x04<<4);
	Port_Init();
	Isr_Init();
	Uart_Init(0, Console_Baud);
	Uart_Select(Console_Uart);	
	EnableModuleClock(CLOCK_ALL);	
	rGPBCON &= ~12;
	rGPBCON |= 4;	
	rGPBDAT |= 2;
	
	led();
}